import React, { useEffect, useState } from "react";
import { motion, useMotionValue, useSpring, useTransform } from "framer-motion";
import { useNavigate } from "react-router-dom";

// 三个竖直排放、左右居中的矩形卡片
// 悬浮时：仅产生倾斜与阴影反馈（不平移）
// 按住后：卡片被“拉扯”，朝鼠标方向有限幅度位移，并伴随倾斜与阴影变化（类似弹簧牵引）
// 页面背景：偏橙色的图片 + 渐变叠加（将图片放到 /public/bg-orange.jpg）

const CARDS = ["我的训练", "创建训练"] as const;

const maxRotate = 6; // deg，最大倾斜角
const hoverInfluenceRadius = 260; // px，悬浮影响半径（仅旋转/阴影）
const dragInfluenceRadius = 320; // px，拖拽影响半径（决定拉扯强度）
const dragMaxTranslate = 46; // px，被拉扯的最大位移

function TugCard({ label, onClick }: { label: string; onClick?: () => void }) {
  const ref = React.useRef<HTMLDivElement | null>(null);
  const [dragging, setDragging] = useState(false);

  // MotionValue + Spring
  const xMV = useMotionValue(0);
  const yMV = useMotionValue(0);
  const rXMV = useMotionValue(0);
  const rYMV = useMotionValue(0);
  const shadowMV = useMotionValue(0.18); // 阴影透明度基线（0.18~0.4）

  const x = useSpring(xMV, { stiffness: 220, damping: 20, mass: 0.6 });
  const y = useSpring(yMV, { stiffness: 220, damping: 20, mass: 0.6 });
  const rotateX = useSpring(rXMV, { stiffness: 170, damping: 16, mass: 0.6 });
  const rotateY = useSpring(rYMV, { stiffness: 170, damping: 16, mass: 0.6 });
  const shadow = useSpring(shadowMV, { stiffness: 170, damping: 18, mass: 0.6 });

  const boxShadow = useTransform(shadow, (s) => {
    const t = Math.max(0, Math.min(1, (s - 0.18) / 0.22)); // 0..1
    const yPx = 6 + 10 * t;
    const blurPx = 18 + 22 * t;
    return `0 ${yPx}px ${blurPx}px rgba(0,0,0,${s.toFixed(2)})`;
  });

  useEffect(() => {
    const onMove = (e: MouseEvent) => {
      const el = ref.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const cx = rect.left + rect.width / 2;
      const cy = rect.top + rect.height / 2;

      const dx = e.clientX - cx;
      const dy = e.clientY - cy;
      const dist = Math.hypot(dx, dy);
      const ux = dx / (dist || 1);
      const uy = dy / (dist || 1);

      if (dragging) {
        const strength = Math.min(1, dist / dragInfluenceRadius);
        const eased = 1 - (1 - strength) * (1 - strength);
        const tx = ux * dragMaxTranslate * eased;
        const ty = uy * dragMaxTranslate * eased;
        xMV.set(tx);
        yMV.set(ty);
        rXMV.set(-(uy * maxRotate * eased));
        rYMV.set(ux * maxRotate * eased);
        shadowMV.set(0.18 + 0.22 * eased);
        return;
      }

      if (dist > hoverInfluenceRadius) {
        xMV.set(0);
        yMV.set(0);
        rXMV.set(0);
        rYMV.set(0);
        shadowMV.set(0.18);
        return;
      }

      const strength = 1 - dist / hoverInfluenceRadius;
      rXMV.set(-(uy * maxRotate * strength));
      rYMV.set(ux * maxRotate * strength);
      shadowMV.set(0.18 + 0.22 * strength);
      xMV.set(0);
      yMV.set(0);
    };

    const onLeave = () => {
      if (dragging) return;
      xMV.set(0);
      yMV.set(0);
      rXMV.set(0);
      rYMV.set(0);
      shadowMV.set(0.18);
    };

    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseleave", onLeave);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseleave", onLeave);
    };
  }, [dragging, xMV, yMV, rXMV, rYMV, shadowMV]);

  const handlePointerDown: React.PointerEventHandler<HTMLDivElement> = (e) => {
    setDragging(true);
    try {
      (e.target as Element).setPointerCapture?.(e.pointerId);
    } catch {}
  };

  const handlePointerUp: React.PointerEventHandler<HTMLDivElement> = (e) => {
    setDragging(false);
    xMV.set(0);
    yMV.set(0);
    rXMV.set(0);
    rYMV.set(0);
    shadowMV.set(0.18);
    try {
      (e.target as Element).releasePointerCapture?.(e.pointerId);
    } catch {}
    onClick?.();
  };

  return (
    <motion.div
      ref={ref}
      className="card-item"
      style={{
        x,
        y,
        rotateX,
        rotateY,
        transformPerspective: 800,
        boxShadow,
        cursor: dragging ? "grabbing" : "pointer",
      }}
      onPointerDown={handlePointerDown}
      onPointerUp={handlePointerUp}
      onPointerCancel={handlePointerUp}
      whileTap={{ scale: 0.995 }}
      role="button"
      tabIndex={0}
    >
      {label}
    </motion.div>
  );
}

export default function Mytraining() {
  const navigate = useNavigate();

  const handleCardClick = (label: string) => {
    if (label === "创建训练") {
      navigate("/mytraining/set");
    } else if (label === "我的训练") {
      navigate("/mytraining/setmy");
    }
  };

  const goBack = () => {
    navigate("/index/training");
  };

  return (
    <div className="mytraining-wrap">
      <style>{`
        .mytraining-wrap {
          --fab-size: 64px; /* 可自行调整圆按钮大小 */
          position: relative;
          min-height: 100vh;
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background-image: url('/bg-orange.jpg');
          background-size: cover;
          background-position: center;
          background-attachment: fixed;
          padding: 40px 16px;
          box-sizing: border-box;
        }
        .back-fab {
          position: fixed; /* 固定在视口，避免被内容覆盖 */
          left: 50%;
          transform: translateX(-50%);
          bottom: 20%;
          width: var(--fab-size);
          height: var(--fab-size);
          border-radius: 50%;
          background: rgb(227, 83, 26);
          display: inline-flex;
          align-items: center;
          justify-content: center;
          border: 2px solid rgba(255,255,255,.45); /* 白色描边增强可见性 */
          box-shadow: 0 8px 24px rgba(0,0,0,0.25);
          cursor: pointer;
          z-index: 1000; /* 确保在最上层 */
        }
        .back-fab:active { transform: scale(0.98); }
        .back-fab svg { width: calc(var(--fab-size) * 0.5); height: calc(var(--fab-size) * 0.5); }
        .back-fab .arrow { fill: rgb(114, 98, 87); }

        .cards-col {
          width: min(720px, 92vw);
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 22px;
        }
        .card-item {
          width: 100%;
          max-width: 640px;
          height: 120px;
          border-radius: 16px;
          background: rgb(229, 80, 26);
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          font-weight: 600;
          letter-spacing: 1px;
          user-select: none;
          will-change: transform, box-shadow;
          box-shadow: 0 6px 18px rgba(0,0,0,0.18);
        }
        @media (max-width: 480px) {
          .card-item { height: 96px; font-size: 20px; }
        }
      `}</style>

      {/* 返回圆形按钮 */}
      <button className="back-fab" aria-label="返回训练" onClick={goBack}>
        <svg viewBox="0 0 24 24" aria-hidden="true">
          <path className="arrow" d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
        </svg>
      </button>

      <div className="cards-col">
        {CARDS.map((label) => (
          <TugCard key={label} label={label} onClick={() => handleCardClick(label)} />
        ))}
      </div>
    </div>
  );
}
